﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace MediaScraper.WindowsService
{
    //http://weblogs.asp.net/kaushal/archive/2011/02/28/start-stop-window-service-from-asp-net-page.aspx
    public static class ScraperController
    {
        public static bool IsRunning()
        {
             
            ServiceController svcController = new ServiceController(ServiceConstants.ServiceName);
            try
            {
                if (svcController.Status == ServiceControllerStatus.Running || svcController.Status == ServiceControllerStatus.StartPending)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
            }
            return false;
        }

        public static void StartService()
        {
            ServiceController svcController = new ServiceController(ServiceConstants.ServiceName);

            try
            {
                if (svcController.Status != ServiceControllerStatus.Running &&
                    svcController.Status != ServiceControllerStatus.StartPending)
                {
                    svcController.Start();
                }
            }
            catch (Exception ex)
            {
                    
            }
        }

        public static void StopService()
        {
            ServiceController svcController = new ServiceController(ServiceConstants.ServiceName);

            try
            {
                if (svcController.Status == ServiceControllerStatus.Running &&
                    svcController.CanStop)
                {
                    svcController.Stop();
                    svcController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
                }
            }
            catch (Exception ex)
            {

            }
        }
    }
}
